package hlinfo.api.wxlogin;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qikecn.api.common.Contents;
import com.qikecn.api.model.BindThirdParty;
import com.qikecn.api.model.User;
import com.qikecn.utils.HtmlUtil;
import com.qikecn.utils.IpUtil;
import com.qikecn.utils.MD5Util;
import com.qikecn.utils.HttpClientUtil;

import it.sauronsoftware.base64.Base64;

/**
 * Servlet implementation class WXLoginBackAction
 */
@WebServlet("/wxloginback.action")
public class WXLoginBackAction extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public WXLoginBackAction() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
		//接收code和state参数
		String code=request.getParameter("code");
		String state=request.getParameter("state");
		WXLoginConfig wxc=new WXLoginConfig();
		//通过code换取access_token
		String url="https://api.weixin.qq.com/sns/oauth2/access_token";
		String params = "appid="+wxc.appid+"&secret="+wxc.appSecret+"&code="+code+"&grant_type=authorization_code";
		System.out.println("url: "+url + params);
		String rstk = HttpClientUtil.sendGet(url, params);
		System.out.println("rstk: "+rstk);
		JSONObject jsontk= JSON.parseObject(rstk);
		//判断是否获取access_token成功
		if(jsontk.containsKey("access_token")) {
			String access_token=jsontk.getString("access_token");
			String openid=jsontk.getString("access_token");
			//通过access_token和openid拉取用户信息(需scope为 snsapi_userinfo)
			String getuserurl="https://api.weixin.qq.com/sns/userinfo";
			params = "access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
			System.out.println("getuserurl: "+getuserurl + params);
			String rsUserInfo=HttpClientUtil.sendGet(getuserurl, params);
			System.out.println("rsUserInfo: "+rsUserInfo);
			JSONObject jsonui= JSON.parseObject(rsUserInfo);
			//判断是否获取用户信息成功
			if(jsonui.containsKey("openid")) {
				//获取用户信息成功
				System.out.println("openid:"+jsonui.getString("openid"));
				System.out.println("nickname:"+jsonui.getString("nickname"));
				System.out.println("sex:"+jsonui.getString("sex"));
				System.out.println("province:"+jsonui.getString("province"));
				System.out.println("city:"+jsonui.getString("city"));
				System.out.println("country:"+jsonui.getString("country"));
				System.out.println("headimgurl:"+jsonui.getString("headimgurl"));
				
				String uid = jsonui.getString("openid");
				String name = jsonui.getString("nickname");
				String gender = jsonui.getString("sex");
				String iconurl = jsonui.getString("headimgurl");
				String accessToken = access_token;
				String refreshToken = jsontk.containsKey("refresh_token")?jsontk.getString("refresh_token"):"";
				String expiration = jsontk.containsKey("expiration")?jsontk.getString("expiration"):"";
				String signTemp = MD5Util.md5("WEIXIN" + uid + name + gender + iconurl + accessToken + Contents.SECRET_KEY );
				
				//1.查询该openid是否已经绑定了帐号，若已经绑定了帐号，直接自动登录成功
				BindThirdParty bindThirdParty = BindThirdParty.dao.findFirst("select id from "+Contents.TAB_PREFIX+"bind_third_party where uid='"+jsonui.getString("openid")+"' and thirdParty='WEIXIN' limit 1");
				if(bindThirdParty != null) {//绑定了帐号
					Map<String, Object> map = User.dao.login("", "", "", "", System.currentTimeMillis()+"", 3, "", "", "WEIXIN", "", "", "", "", "WEIXIN", uid, name, gender, iconurl, accessToken, refreshToken, expiration, signTemp, IpUtil.getRemoteIp(request));
					if( map.get("ret").toString().equals("200") ) {
						String path = request.getContextPath();int port = request.getServerPort();
						String basePath = (port==80 || port==443)?request.getScheme()+"://"+request.getServerName()+path+"/":request.getScheme()+"://"+request.getServerName()+":"+port+path+"/";
						Map<String, Object> userMap = (Map<String, Object>)map.get("user");
						response.sendRedirect( basePath + "mobile/photoBook?key="+userMap.get("key")+"&zongji="+userMap.get("zongji") );
						return;//登录成功
					}
				}
				//登录失败或未绑定，跳转到帐号、密码登录页面
				String path = request.getContextPath();int port = request.getServerPort();
				String basePath = (port==80 || port==443)?request.getScheme()+"://"+request.getServerName()+path+"/":request.getScheme()+"://"+request.getServerName()+":"+port+path+"/";
				//去掉昵称中的表情符号
				name = HtmlUtil.filterEmoji(name);
				String thirdParty = "WEIXIN";
				String sign = MD5Util.md5(thirdParty + uid + name + gender + iconurl + accessToken + Contents.SECRET_KEY );
				response.sendRedirect( basePath + "mobile/login?thirdParty="+thirdParty+"&uid="+uid+"&name="+Base64.encode(name, "UTF-8")+"&gender="+Base64.encode(gender, "UTF-8")+"&iconurl="+Base64.encode(iconurl, "UTF-8")+"&accessToken="+accessToken+"&sign="+sign );
			}else {
				//获取用户信息失败
				
				//跳转到帐号、密码登录页面
				String path = request.getContextPath();int port = request.getServerPort();
				String basePath = (port==80 || port==443)?request.getScheme()+"://"+request.getServerName()+path+"/":request.getScheme()+"://"+request.getServerName()+":"+port+path+"/";
				response.sendRedirect(basePath + "mobile/login");
			}
		}else {
			//获取access_token失败
			
			//跳转到帐号、密码登录页面
			String path = request.getContextPath();int port = request.getServerPort();
			String basePath = (port==80 || port==443)?request.getScheme()+"://"+request.getServerName()+path+"/":request.getScheme()+"://"+request.getServerName()+":"+port+path+"/";
			response.sendRedirect(basePath + "mobile/login");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
